#!/bin/sh
# 编译安装管理Resin
App=resin
AppName=Resin
AppBase=/App
AppDir=$AppBase/$App
AppProg=$AppDir/bin/resin.sh

AppSrcBase=/App/src
AppSrcFile=$App-*.tar.*
AppSrcDir=$(find $AppSrcBase -maxdepth 1 -name "$AppSrcFile" -type f 2> /dev/null | sed -e 's/.tar.*$//' -e 's/^.\///')

RemoveFlag=0
InstallFlag=0


# 查询状态
fstatus()
{
    if [ ! -f "$AppProg" ]; then
        echo "$AppName 未安装"
    else
        echo "$AppName 已安装"
    fi
}

# 删除
fremove()
{
    RemoveFlag=1

    if [ -d "$AppDir" ]; then
        rm -rf $AppDir && echo "删除 $AppName"
    else
        echo "$AppName 未安装"
    fi
}

# 备份
fbackup()
{
    Day=$(date +%Y-%m-%d)
    BackupFile=$App-$Day.tgz

    if [ -f "$AppProg" ]; then
        cd $AppBase
        tar zcvf $BackupFile --exclude=logs/* $App --backup=numbered
        [ $? -eq 0 ] && echo "$AppName 备份成功" || echo "$AppName 备份失败"
    else
        echo "$AppName 未安装" 
    fi
}

# 安装
finstall()
{
    InstallFlag=1

    test -f "$AppProg" && echo "$AppName 已安装" 
    [ $? -ne 0 ] && fupdate
}

# 更新
fupdate()
{
    Operate="更新"
    [ $InstallFlag -eq 1 ] && Operate="安装"
    [ $RemoveFlag -ne 1 ] && fbackup

    cd $AppSrcBase
    test -d "$AppSrcDir" && rm -rf $AppSrcDir

    tar zxf $AppSrcFile || tar jxf $AppSrcFile
    cd $AppSrcDir

    ./configure \
    "--prefix=$AppDir" \
    "--enable-64bit"

    [ $? -eq 0 ] && make && make install

    if [ $? -eq 0 ]; then
        echo "$AppName $Operate成功"
        rm -rf $AppDir/log $AppDir/webapps/ROOT
        mkdir -p /opt/log/resin-log
        ln -s /opt/log/resin-log $AppDir/log
    else
        echo "$AppName $Operate失败"
        exit 1
    fi
}


ScriptDir=$(dirname $0)
ScriptFile=$(basename $0)
case "$1" in
    "install"   ) finstall;;
    "update"    ) fupdate;;
    "reinstall" ) fremove && finstall;;
    "remove"    ) fremove;;
    "backup"    ) fbackup;;
    "status"    ) fstatus;;
    *           )
    echo "$ScriptFile install              安装 $AppName"
    echo "$ScriptFile update               更新 $AppName"
    echo "$ScriptFile reinstall            重装 $AppName"
    echo "$ScriptFile remove               删除 $AppName"
    echo "$ScriptFile backup               备份 $AppName"
    echo "$ScriptFile status               查询 $AppName 状态"
    ;;
esac
